package com.zr.task.presenter;


import android.Manifest;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.lurencun.service.autoupdate.AppUpdateService;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.model.TaskModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.netutils.HRetrofitNetHelper;
import com.zh.baselibrary.netutils.NetUtil;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.home.TokenBean;
import com.zr.task.R;
import com.zr.task.TaskApplication;
import com.zr.task.activity.BidActivity;
import com.zr.task.activity.LimitActivity;
import com.zr.task.activity.QRCodeActivity;
import com.zr.task.activity.TaskMainActivity;
import com.zr.task.adapter.HomeCabinetAdapter;
import com.zr.task.constant.Constant;
import com.zr.task.service.HeartService;
import com.zr.task.utils.DeviceUtil;
import com.zr.task.websocket.AppResponseDispatcher;
import com.zr.websocket.WebSocketSend;
import com.zr.websocket.WebSocketService;
import com.zr.websocket.WebSocketSetting;


import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static android.content.Context.ALARM_SERVICE;

public class LoginPresenter extends BasePresenter {
    private TaskModel model;
    private boolean hasStart = false;

    @Override
    public void attachModel(Context context) {
        model = new TaskModel(context);
    }

    public void login() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Observable<BaseResp<TokenBean>> observable = getObservableNotStop(model.equipmentLogin(DeviceUtil.getEquipmentLogin(getContext())));
                observable.subscribe(new RxSubscribe<BaseResp<TokenBean>>() {
                    @Override
                    public void onSuccess(BaseResp<TokenBean> baseResp) throws Exception {

                    }

                    @Override
                    public void onHint(String hint) {

                    }
                });
            }
        }).start();

    }

    public void permissionCheck() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
                != PackageManager.PERMISSION_GRANTED
        ) {
            requestEachRxPermission(Manifest.permission.READ_PHONE_STATE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
        } else {
            startHeart();
        }
    }

    private void requestEachRxPermission(String... permissions) {
        RxPermissions rxPermissions = new RxPermissions((Activity) getContext());
        rxPermissions.requestEach(permissions).subscribe((Action1<? super Permission>) permission -> {
            if (permission.granted) {

                startHeart();
            } else if (permission.shouldShowRequestPermissionRationale) {
                //拒绝权限请求
                Toast.makeText(getContext(), "已拒绝权限" + permission.name, Toast.LENGTH_SHORT).show();
            } else {
                // 拒绝权限请求,并不再询问
                // 可以提醒用户进入设置界面去设置权限
                Toast.makeText(getContext(), "已拒绝权限" + permission.name + "并不再询问", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void startHeart() {

        if (NetUtil.checkNetwork(getContext()) == NetUtil.NO_NETWORK) {
            ToastView.showLong("网络无法访问，请检查网络连接");
        } else {
            //配置 WebSocket，必须在 WebSocket 服务启动前设置
            if (!hasStart) {
                hasStart = true;
                String uuId = PhoneUtil.getUUID(getContext());
                WebSocketSetting.setConnectUrl(HRetrofitNetHelper.getWebSocketUrl() + uuId);//必选
                WebSocketSetting.setResponseProcessDelivery(new AppResponseDispatcher(getContext()));
                WebSocketSetting.setReconnectWithNetworkChanged(true);
                //启动 WebSocket 服务
                ShareManager.setValue(getContext(), "websocket", HRetrofitNetHelper.getWebSocketUrl() + uuId);
                getContext().startService(new Intent(getContext(), WebSocketService.class));
                EventBus.getDefault().post(new WebSocketSend("", "set"));

            }
        }
        startHome();
    }

    private void startHome() {
        //  ShareManager.setLong(getContext(),BaseConstant.AUTHORIZATION_DEADLINE,1676647458882l);
        TTSUtils.getInstance().init(TaskApplication.getContext());
        Long deadLine = ShareManager.getLong(getContext(), BaseConstant.AUTHORIZATION_DEADLINE);
        int lockStatus = ShareManager.getInt(getContext(), BaseConstant.DEVICE_LOCK_TYPE);
        if (lockStatus == 1) {
            Bundle bundle = new Bundle();
            bundle.putInt(ExtraName.KEY_DATA, 2);
            getContext().stopService(new Intent(getContext(), HeartService.class));
            getContext().startService(new Intent(getContext(), HeartService.class));
            IntentUtils.instance().startActivity(getContext(), LimitActivity.class, bundle);
            login();

        } else {
            if (deadLine == null || deadLine == 0 || deadLine == -1) {
                IntentUtils.instance().startActivity(getContext(), QRCodeActivity.class);
            } else {
                getContext().stopService(new Intent(getContext(), HeartService.class));
                getContext().startService(new Intent(getContext(), HeartService.class));
                if (Constant.isBid)
                    IntentUtils.instance().startActivity(getContext(), BidActivity.class);
                else
                    IntentUtils.instance().startActivity(getContext(), TaskMainActivity.class);
                login();
            }
        }
        ((Activity) getContext()).finish();
    }

}
